package com.ebelter.bodyfatscale.ui.pager.main;

import android.app.Activity;
import android.content.Intent;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.ebelter.bodyfatscale.R;
import com.ebelter.bodyfatscale.adapter.TrendHLvAdapter;
import com.ebelter.bodyfatscale.common.Constants;
import com.ebelter.bodyfatscale.moudules.beans.ComputerMesureData;
import com.ebelter.bodyfatscale.moudules.db.Daos;
import com.ebelter.bodyfatscale.moudules.db.beans.HistoryMesureDataAvg;
import com.ebelter.bodyfatscale.ui.activity.HistoryListActivity;
import com.ebelter.bodyfatscale.ui.view.EndlessRecyclerOnScrollListener;
import com.ebelter.bodyfatscale.ui.view.HoriLineView;
import com.ebelter.bodyfatscale.ui.view.combinviews.CombinView1;
import com.ebelter.bodyfatscale.util.BaseHandle;
import com.ebelter.bodyfatscale.util.NumUtils;
import com.ebelter.bodyfatscale.util.ScaleBaseUtils;
import com.ebelter.bodyfatscale.util.StringUtils;
import com.ebelter.bodyfatscale.util.ThreadManager;
import com.ebelter.bodyfatscale.util.UserSpUtil;
import com.ebelter.bodyfatscale.util.ViewUtils;
import com.ebelter.btlibrary.util.ULog;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.TreeMap;

import butterknife.BindView;
public class TrendsPager extends BasePagerMain implements RadioGroup.OnCheckedChangeListener {


    private static final String TAG = "TrendsPager";



    public static final int TYPE_WEIGHT = 1;
    public static final int TYPE_BODYFAT = 2;
    public static final int TYPE_MUSCLE = 3;

    public static final int TIME_DAY = 4;
    public static final int TIME_WEEK = 5;
    public static final int TIME_MONTH = 6;

    private String avg_weight_day;
    private String avg_weight_week;
    private String avg_weight_month;
    private String avg_bfp_day;
    private String avg_bfp_week;
    private String avg_bfp_month;
    private String avg_mass_day;
    private String avg_mass_week;
    private String avg_mass_month;
    private String change_weight;
    private String change_bodyfat_percentage;
    private String change_muscle_mass;

    private String unitKg = StringUtils.getResStr(R.string.kg);
    private String unitLb = StringUtils.getResStr(R.string.lb);

    private BaseHandle mBaseHandle;

    private void getStrs(){
        avg_weight_day=StringUtils.getResStr(R.string.avg_weight_day);
        avg_weight_week=StringUtils.getResStr(R.string.avg_weight_week);
        avg_weight_month=StringUtils.getResStr(R.string.avg_weight_month);
        avg_bfp_day=StringUtils.getResStr(R.string.avg_bfp_day);
        avg_bfp_week=StringUtils.getResStr(R.string.avg_bfp_week);
        avg_bfp_month=StringUtils.getResStr(R.string.avg_bfp_month);
        avg_mass_day=StringUtils.getResStr(R.string.avg_mass_day);
        avg_mass_week=StringUtils.getResStr(R.string.avg_mass_week);
        avg_mass_month=StringUtils.getResStr(R.string.avg_mass_month);
        change_weight=StringUtils.getResStr(R.string.change_weight);
        change_bodyfat_percentage=StringUtils.getResStr(R.string.change_bodyfat_percentage);
        change_muscle_mass=StringUtils.getResStr(R.string.change_muscle_mass);
    }


    private int currentDisplayType;
    private int currentDisplayTime;//4day 5weeeks 6month


    @BindView(R.id.trend_gongneng_rg)
    RadioGroup trend_gongneng_rg;

    @BindView(R.id.trend_time_rg)
    RadioGroup trend_time_rg;

//    @BindView(R.id.trend_chartView)
//    ChartView trend_chartView;

    @BindView(R.id.trend_time_left_iv)
    ImageView trend_time_left_iv;

    @BindView(R.id.trend_time_tv)
    TextView trend_time_tv;

    @BindView(R.id.trend_time_right_iv)
    ImageView trend_time_right_iv;

    @BindView(R.id.trend_unit_time_tv)
    TextView trend_unit_time_tv;

    @BindView(R.id.trend_avg_weight_cb1)
    CombinView1 trend_avg_weight_cb1;

    @BindView(R.id.trend_change_weight_cb1)
    CombinView1 trend_change_weight_cb1;


    //历史记录
    @BindView(R.id.trends_topright_iv)
    ImageView trends_topright_iv;


    @BindView(R.id.horlineview)
    HoriLineView horiLineView;

    @BindView(R.id.trend_hlv)
    RecyclerView trend_hlv;
    private TrendHLvAdapter trendHLvAdapter;




    private String unit_p1;
    private String unit_p2;

    public TrendsPager(Activity context) {
        super(context);
        mBaseHandle = new BaseHandle(context);
        mBaseHandle.setMsgCallBack(new BaseHandle.IHandleMsgCallBack() {
            @Override
            public void handleMsg(Message msg) {
                handleMsg1(msg);
            }
        });
    }


    private void handleMsg1(Message msg){

    }

    @Override
    protected int loadLayoutById() {
        return R.layout.pager_trends;
    }

    @Override
    public void initViews() {

        getStrs();

        initCharView();
        setListeners();
        horiLineView.setDisplay(true);//设置横线为可以显示
        ViewUtils.displayView(horiLineView);

        currentDisplayType = TYPE_WEIGHT;
        currentDisplayTime = TIME_DAY;

        unit_p1 = Constants.isKgUnit?StringUtils.getResStr(R.string.kg):StringUtils.getResStr(R.string.lb);
        unit_p2 = StringUtils.getResStr(R.string.day);
        disPlayUnit();
        setTrendHLvAdapterDisPlayStyle();
        requestDisplayData(true);

        trends_topright_iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openHistoryDatas();
            }
        });
    }



    //打开历史记录数据
    private void openHistoryDatas() {
        Intent intent = new Intent(getActivity(), HistoryListActivity.class);
        getActivity().startActivity(intent);
    }

    private void setListeners() {
        trend_gongneng_rg.setOnCheckedChangeListener(this);
        trend_time_rg.setOnCheckedChangeListener(this);


       // 设置加载更多监听
        trend_hlv.addOnScrollListener(new EndlessRecyclerOnScrollListener() {
            @Override
            public void onLoadMore(boolean isSlidingToLeft) {
                // 加载更多
                ULog.e(TAG,"-----onLoadMore() isSlidingToLeft = " + isSlidingToLeft);
                if (!isSlidingToLeft){
                    requestDisplayData(false);
                }
            }
        });

    }

    private void initCharView() {

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        trend_hlv.setLayoutManager(linearLayoutManager);


        trendHLvAdapter = new TrendHLvAdapter(getActivity());
        trend_hlv.setAdapter(trendHLvAdapter);


    }

    @Override
    public void initData(Object data) {

    }

    @Override
    public void switchUnitUpdate() {
        updateCb1Title1();
        if (currentDisplayType==TYPE_WEIGHT||currentDisplayType==TYPE_MUSCLE){
            unit_p1=Constants.isKgUnit?unitKg:unitLb;
        }else if (currentDisplayType==TYPE_BODYFAT){
            unit_p1="%";
        }
        disPlayUnit();
        displayTargetWeightLine();
    }


    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {

        switch (checkedId){
                case R.id.gnrg_weight://体重
                    currentDisplayType=TYPE_WEIGHT;
                    unit_p1 = Constants.isKgUnit?unitKg:unitLb;
                    ViewUtils.displayView(horiLineView);
                    displayTargetWeightLine();
                    break;
                case R.id.gnrg_bodyfat://脂肪
                    currentDisplayType=TYPE_BODYFAT;
                    unit_p1 = StringUtils.getResStr(R.string.p);
                    ViewUtils.hideView(horiLineView);
                    break;
                case R.id.gnrg_musclemass://肌肉
                    currentDisplayType=TYPE_MUSCLE;
                    unit_p1 =Constants.isKgUnit?unitKg:unitLb;
                    ViewUtils.hideView(horiLineView);
                    break;
                case R.id.trg_day:
                    currentDisplayTime=TIME_DAY;//日
                    unit_p2 = StringUtils.getResStr(R.string.day);
                    break;
                case R.id.trg_week://周
                    currentDisplayTime=TIME_WEEK;
                    unit_p2 = StringUtils.getResStr(R.string.week);
                    break;
                case R.id.trg_month://天
                    currentDisplayTime=TIME_MONTH;
                    unit_p2 = StringUtils.getResStr(R.string.month);
                    break;
        }
        setTrendHLvAdapterDisPlayStyle();//设置Adapter的显示类型
        disPlayUnit();//显示单位
        updateCb1Title1();//更新组合控件1
        if (trend_gongneng_rg==group){
            switchDisplayData();
        }else if (trend_time_rg==group){//说明点击的是时间控件了
            ULog.i(TAG,"点击了时间控件Rg");
            requestDisplayData(true);
        }

    }



    //更新title1
    private void updateCb1Title1() {
        String title11="";
        String title21="";
        String title12="";
        String title22="";
        String title13="";

        if (currentDisplayTime==TIME_DAY){
            switch (currentDisplayType){
                case TYPE_WEIGHT:
                    title11=avg_weight_day; //日均体重
                    title21=change_weight;  //体重变化

                    title12=trendHLvAdapter!=null?NumUtils.numBaoLiuWei(ScaleBaseUtils.adapterDataFloat((float) trendHLvAdapter.getAvg(TIME_DAY,TYPE_WEIGHT)),1)+"":"";
                    title22=trendHLvAdapter!=null?NumUtils.numBaoLiuWei(trendHLvAdapter.getChange(TIME_DAY,TYPE_WEIGHT),1)+"":"";
                    title13=Constants.isKgUnit?unitKg:unitLb;;
                    break;
                case TYPE_BODYFAT:
                    title11=avg_bfp_day;
                    title21=change_bodyfat_percentage;

                    title12=trendHLvAdapter!=null?NumUtils.numBaoLiuWei((float) trendHLvAdapter.getAvg(TIME_DAY,TYPE_BODYFAT),1)+"":"";
                    title22=trendHLvAdapter!=null?NumUtils.numBaoLiuWei(trendHLvAdapter.getChange(TIME_DAY,TYPE_BODYFAT),1)+"":"";
                    title13="%";
                    break;
                case TYPE_MUSCLE:
                    title11=avg_mass_day;
                    title21=StringUtils.getResStr(R.string.change_muscle_mass);

                    title12=trendHLvAdapter!=null?NumUtils.numBaoLiuWei(ScaleBaseUtils.adapterDataFloat((float) trendHLvAdapter.getAvg(TIME_DAY,TYPE_MUSCLE)),1)+"":"";
                    title22=trendHLvAdapter!=null?NumUtils.numBaoLiuWei(trendHLvAdapter.getChange(TIME_DAY,TYPE_MUSCLE),1)+"":"";
                    title13=Constants.isKgUnit?unitKg:unitLb;
                    break;
            }

        }else if (currentDisplayTime==TIME_WEEK){
            switch (currentDisplayType){
                case TYPE_WEIGHT:
                    title11=avg_weight_week;
                    title21=change_weight;
                    title12=trendHLvAdapter!=null?NumUtils.numBaoLiuWei(ScaleBaseUtils.adapterDataFloat((float) trendHLvAdapter.getAvg(TIME_WEEK,TYPE_WEIGHT)),1)+"":"";
                    title22=trendHLvAdapter!=null?NumUtils.numBaoLiuWei((float) trendHLvAdapter.getChange(TIME_WEEK,TYPE_WEIGHT),1)+"":"";
                    title13=Constants.isKgUnit?unitKg:unitLb;
                    break;
                case TYPE_BODYFAT:
                    title11=avg_bfp_week;
                    title21=change_bodyfat_percentage;

                    title12=trendHLvAdapter!=null?NumUtils.numBaoLiuWei((float) trendHLvAdapter.getAvg(TIME_WEEK,TYPE_BODYFAT),1)+"":"";
                    title22=trendHLvAdapter!=null?NumUtils.numBaoLiuWei((float) trendHLvAdapter.getChange(TIME_WEEK,TYPE_BODYFAT),1)+"":"";
                    title13="%";
                    break;
                case TYPE_MUSCLE:
                    title11=avg_mass_week;
                    title21=change_muscle_mass;

                    title12=trendHLvAdapter!=null?NumUtils.numBaoLiuWei(ScaleBaseUtils.adapterDataFloat((float) trendHLvAdapter.getAvg(TIME_WEEK,TYPE_MUSCLE)),1)+"":"";
                    title22=trendHLvAdapter!=null?NumUtils.numBaoLiuWei(trendHLvAdapter.getChange(TIME_WEEK,TYPE_MUSCLE),1)+"":"";
                    title13=Constants.isKgUnit?unitKg:unitLb;
                    break;
            }

        }else if(currentDisplayTime==TIME_MONTH){
            switch (currentDisplayType){
                case TYPE_WEIGHT:
                    title11=avg_weight_month;
                    title21=change_weight;

                    title12=trendHLvAdapter!=null?NumUtils.numBaoLiuWei(ScaleBaseUtils.adapterDataFloat((float) trendHLvAdapter.getAvg(TIME_MONTH,TYPE_WEIGHT)),1)+"":"";
                    title22=trendHLvAdapter!=null?NumUtils.numBaoLiuWei(trendHLvAdapter.getChange(TIME_MONTH,TYPE_WEIGHT),1)+"":"";
                    title13=Constants.isKgUnit?unitKg:unitLb;
                    break;
                case TYPE_BODYFAT:
                    title11=avg_bfp_month;
                    title21=change_bodyfat_percentage;

                    title12=trendHLvAdapter!=null?NumUtils.numBaoLiuWei((float) trendHLvAdapter.getAvg(TIME_MONTH,TYPE_BODYFAT),1)+"":"";
                    title22=trendHLvAdapter!=null?NumUtils.numBaoLiuWei(trendHLvAdapter.getChange(TIME_MONTH,TYPE_BODYFAT),1)+"":"";
                    title13="%";
                    break;
                case TYPE_MUSCLE:
                    title11=avg_mass_month;
                    title21=change_muscle_mass;

                    title12=trendHLvAdapter!=null?NumUtils.numBaoLiuWei(ScaleBaseUtils.adapterDataFloat((float) trendHLvAdapter.getAvg(TIME_MONTH,TYPE_MUSCLE)),1)+"":"";
                    title22=trendHLvAdapter!=null?NumUtils.numBaoLiuWei( trendHLvAdapter.getChange(TIME_MONTH,TYPE_MUSCLE),1)+"":"";
                    title13=Constants.isKgUnit?unitKg:unitLb;
                    break;
            }

        }

        if (trend_avg_weight_cb1!=null){
            trend_avg_weight_cb1.setTitle1(title11);
            trend_avg_weight_cb1.setTitle2(title12);
            trend_avg_weight_cb1.setTitle3(title13);
        }
        if (trend_change_weight_cb1!=null){
            trend_change_weight_cb1.setTitle1(title21);
            trend_change_weight_cb1.setTitle2(title22);
            trend_change_weight_cb1.setTitle3(title13);
        }

    }

    //显示体重
    private void disPlayUnit(){
        if (trend_unit_time_tv!=null){
            trend_unit_time_tv.setText(unit_p1);
        }
    }




    //请求趋势界面的平均数据
    public void requestDisplayData(final boolean scroll2end) {



        ThreadManager.getShortPool().execute(new Runnable() {
            @Override
            public void run() {
                ULog.i(TAG, "-------requestDisplayData()------currentDisplayTime = "+currentDisplayTime+"-------currentDisplayType = "+currentDisplayType);
                long userid = UserSpUtil.readLong(Constants.IUser.USER_ID);
                List<HistoryMesureDataAvg> datas = Daos.getInstance().getUserAvgDatas(userid,true);
                final int time = currentDisplayTime;
                final List<ComputerMesureData> result = computer(datas,time);


                if (mBaseHandle!=null){
                    mBaseHandle.post(new Runnable() {
                        @Override
                        public void run() {
                            displayData(result,time,scroll2end);
                        }
                    });
                }







            }
        });







        final int whichTime;
        if (currentDisplayTime==TIME_DAY){
            whichTime=1;
        }else if (currentDisplayTime==TIME_WEEK){
            whichTime=2;
        }else if (currentDisplayTime==TIME_MONTH){
            whichTime=3;
        }else {
            return;
        }

        displayData(null,whichTime,scroll2end);


    }



    //计算时间
    private List<ComputerMesureData> computer(List<HistoryMesureDataAvg> dataAvgs,int Time){
        List<ComputerMesureData> result = new ArrayList<>();
        if (Time == TIME_DAY){
            for (HistoryMesureDataAvg avg:dataAvgs){
                ComputerMesureData c = new ComputerMesureData();
                c.setAvgWeight(avg.weight);
                c.setAvgMQ(avg.muscleVolume);
                c.setAvgAR(avg.fat);
                c.setDays(avg.measureTime);
                result.add(c);
            }

        }else if (Time==TIME_WEEK){
            TreeMap<String,List<HistoryMesureDataAvg>> timeMaps = new TreeMap<>();
            for (HistoryMesureDataAvg avg:dataAvgs){
                String time = timeTransformation(avg.measureTime,0);
                if (!TextUtils.isEmpty(time)){
                    if (timeMaps.containsKey(time)){
                        List<HistoryMesureDataAvg> temp = timeMaps.get(time);
                        temp.add(avg);
                    }else {
                        List<HistoryMesureDataAvg> temp = new ArrayList<>();
                        temp.add(avg);
                        timeMaps.put(time,temp);
                    }
                }
            }
            Iterator it = timeMaps.keySet().iterator();
            while (it.hasNext()) {
                //it.next()得到的是key，tm.get(key)得到obj
                String key= (String) it.next();
                List<HistoryMesureDataAvg>  t2 = timeMaps.get(key);
                ComputerMesureData re = avgHistoryMesureDataAvg(t2);
                if (re!=null){
                    re.setDays(key);
                    result.add(re);
                }
            }
        }else if (Time==TIME_MONTH){
            TreeMap<String,List<HistoryMesureDataAvg>> timeMaps = new TreeMap<>();
            for (HistoryMesureDataAvg avg:dataAvgs){
                String time = timeTransformation(avg.measureTime,1);
                if (!TextUtils.isEmpty(time)){
                    if (timeMaps.containsKey(time)){
                        List<HistoryMesureDataAvg> temp = timeMaps.get(time);
                        temp.add(avg);
                    }else {
                        List<HistoryMesureDataAvg> temp = new ArrayList<>();
                        temp.add(avg);
                        timeMaps.put(time,temp);
                    }
                }
            }

            Iterator it = timeMaps.keySet().iterator();
            while (it.hasNext()) {
                //it.next()得到的是key，tm.get(key)得到obj
                String key= (String) it.next();
                List<HistoryMesureDataAvg>  t2 = timeMaps.get(key);
                ComputerMesureData re = avgHistoryMesureDataAvg(t2);
                if (re!=null){
                    re.setDays(key);
                    result.add(re);
                }

            }
        }
        return result;
    }



    //计算集合的均值
    private ComputerMesureData avgHistoryMesureDataAvg(List<HistoryMesureDataAvg> datas){

        ComputerMesureData result = null;

        float fat=0;
        float weight=0;
        float muscle=0;
        for(HistoryMesureDataAvg t:datas){
            fat+=t.fat;
            weight+=t.weight;
            muscle+=t.muscleVolume;
        }
        if (datas.size()>0){
            fat = fat/datas.size();
            weight = weight/datas.size();
            muscle = muscle/datas.size();

            result = new ComputerMesureData();
            result.setAvgAR(fat);
            result.setAvgWeight(weight);
            result.setAvgMQ(muscle);
        }

        return result;

    }


    //mesureTime 2018-10-10
    private String timeTransformation(String mesureTime,int timeStyle){
        String resultTime;
        if (timeStyle==0){//weeks
            try {
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                Date date = format.parse(mesureTime);
                Calendar calendar = Calendar.getInstance();
                calendar.setFirstDayOfWeek(Calendar.MONDAY);
                calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);// 每周从周一开始
                calendar.setTime(date);
                calendar.setMinimalDaysInFirstWeek(7); // 设置每周最少为7天
                int week = calendar.get(Calendar.WEEK_OF_YEAR);

                String temp;
                if (week<10){
                    temp="0"+week;
                }else {
                    temp=""+week;
                }
                resultTime = mesureTime.substring(0,5) + temp;
                return resultTime;
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }else {//months
            return mesureTime.substring(0,7);
        }
        return null;
    }







    private void setTrendHLvAdapterDisPlayStyle(){
        if (trendHLvAdapter!=null){
            trendHLvAdapter.setCurrentDisplayType(currentDisplayType);
            trendHLvAdapter.setCurrentDisplayTimeType(currentDisplayTime);
        }
    }



    //显示数据 whichTime 1DAY 2WEEK 3MONTH
    private void displayData(final List<ComputerMesureData> resultData,int whichTime,final boolean scroll2end) {
        ULog.i(TAG,"---displayData---A--whichTime="+whichTime);
        if (resultData==null){
            return;
        }
        if (trendHLvAdapter!=null){
            trendHLvAdapter.setCurrentDisplayType(currentDisplayType);
            trendHLvAdapter.addDatas(resultData,whichTime);
            if (scroll2end){
                ViewUtils.recyclerViewScrollToPosition(trend_hlv,trendHLvAdapter.getItemCount()-1);
            }
            displayTargetWeightLine();//更新目标体重的横线
            updateCb1Title1();
        }
    }


    //显示目标体重横线
    public void displayTargetWeightLine(){
        ULog.i(TAG,"---displayTargetWeightLine---A");
        if (horiLineView==null){
            return;
        }
        ULog.i(TAG,"---displayTargetWeightLine---B");
        if (trendHLvAdapter!=null && trendHLvAdapter.getItemCount()!=0){
            ULog.i(TAG,"---displayTargetWeightLine---C");
            horiLineView.setDisplay(true);
            float p;
            String displayText="";
            trendHLvAdapter.calculator();//计算一遍的意思 计算中集合中最大的值出来
            if (trendHLvAdapter.maxWeight<=0){
                    p=0;
            }else {
                    float targetWeight = UserSpUtil.readFloat(Constants.IUser.TARGET_WEIGHT);
                    p= targetWeight/trendHLvAdapter.maxWeight;//zcq 注意这里
                    displayText=NumUtils.numBaoLiuWei(ScaleBaseUtils.adapterDataFloat(targetWeight),1)+"";
            }
            ULog.i(TAG,"---displayTargetWeightLine---D--p="+p+"---displayText="+displayText);
            horiLineView.setPercentage(p);
            if (p==0){
                horiLineView.setDisplay(false);
            }
            horiLineView.setDisplayText(displayText);
        }else {
            horiLineView.setDisplay(false);
        }
        horiLineView.show();
    }





    private void switchDisplayData() {

        ULog.i(TAG, "-------currentDisplayTime = "+currentDisplayTime+"-------currentDisplayType = "+currentDisplayType);



    }



}
